package com.swt.gap.controller;

import com.swt.gap.common.constant.CommonConstant;
import com.swt.gap.model.entity.SysIcon;
import com.swt.gap.model.vo.IconVO;
import com.swt.gap.model.vo.UploadFileVO;
import com.swt.gap.service.SysIconService;
import com.swt.gap.service.UploadService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;

/**
 * 生产环境 采用rainbond环境，前端通过nginx代理，导致上传相关接口无法正常使用，统一增加api前缀
 */
@Api(tags = "上传 相关接口")
@RestController
@RequestMapping("/api")
@Slf4j
public class UploadController {
    private final UploadService uploadService;

    private final SysIconService sysIconService;

    public UploadController(SysIconService sysIconService, UploadService uploadService) {
        this.sysIconService = sysIconService;
        this.uploadService = uploadService;
    }

    @PostMapping("/icon/icons")
    @ApiOperation(value = "上传并保存icon", notes = "上传并保存icon")
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = SysIcon.class, responseContainer = "List")})
    public ResponseEntity uploadEntityIcon(@RequestParam("files") MultipartFile[] files) {
        return ResponseEntity.ok(sysIconService.addIcon(files, CommonConstant.ICON_PATH));
    }

    @PostMapping("/icon/icons/draw")
    @ApiOperation(value = "画图上传", notes = "画图上传")
    @ApiResponses({@ApiResponse(code = 200, message = "ok", response = IconVO.class, responseContainer = "List")})
    public ResponseEntity uploadPaintIcon(@RequestParam("files") MultipartFile[] files) {
        return ResponseEntity.ok(sysIconService.addPaintIcon(files, CommonConstant.ICON_PATH));
    }

    @ApiOperation(value = "导入子图，上传swtg文件", notes = "上传swtg文件")
    @PostMapping("/graph/upload")
    public ResponseEntity<String> parseXML(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFileName = file.getOriginalFilename();
        assert originalFileName != null;
        if (originalFileName.endsWith(".swtg")) {
            Reader reader = new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8);
            int ch = 0;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            String content = sb.toString();
            return ResponseEntity.ok(content);
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("文件格式不正确");
    }

    @PostMapping("/file/upload")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "formData", dataType = "MultipartFile", name = "file", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "fileClassId", value = "数据类别id")
    })
    @ApiResponses({@ApiResponse(code = 201, message = "CREATED", response = UploadFileVO.class),
            @ApiResponse(code = 406, message = "格式不支持"),
            @ApiResponse(code = 404, message = "原始文件不存在"),
            @ApiResponse(code = 500, message = "系统问题"),
            @ApiResponse(code = 409, message = "已重名"),
            @ApiResponse(code = 400, message = "文件大小为0kb,为空文件")})
    public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file, @RequestParam int fileClassId) {
        //  文件存项目路径下
        UploadFileVO uploadFileVO = null;
        try {
            uploadFileVO = uploadService.uploadFile(file, fileClassId);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("系统问题，请联系管理员");
        }
        if (!uploadFileVO.getUploadSuccess()) {
            if (uploadFileVO.getFailedFile().getErrorCode().equals(1)) {
                return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(uploadFileVO);
            } else if (uploadFileVO.getFailedFile().getErrorCode().equals(2)) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(uploadFileVO);
            } else if (uploadFileVO.getFailedFile().getErrorCode().equals(3)) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(uploadFileVO);
            } else if (uploadFileVO.getFailedFile().getErrorCode().equals(4)) {
                return ResponseEntity.status(HttpStatus.CONFLICT).body(uploadFileVO);
            } else if (uploadFileVO.getFailedFile().getErrorCode().equals(5)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(uploadFileVO);
            }
        }
        return ResponseEntity.status(HttpStatus.CREATED).body(uploadFileVO);
    }
}
